package com.jarchie.seemovies.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * Created by Jarchie on 2017\11\20.
 * 描述：处理图片转换的工具类
 */

public class ImageUtils {

    /**
     * 保存头像到ShareUtil里面
     *
     * @param mContext
     * @param imageView
     */
    public static void putImageToShareUtil(Context mContext, ImageView imageView) {
        BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        //第一步:将Bitmap压缩成字节数组输出流
        ByteArrayOutputStream byStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byStream);
        //第二步:利用Base64将我们的字节数组输出流转换成String
        byte[] byteArray = byStream.toByteArray();
        String imageString = Base64.encodeToString(byteArray, Base64.DEFAULT);
        //第三部:将String保存到ShareUtils里面
        SharePreUtils.putString(mContext, Constant.IMAGE_TITLE, imageString);
    }

    /**
     * 从ShareUtil里面读出图片设置到ImageView上面
     *
     * @param mContext
     * @param imageView
     */
    public static void getImageFromShareUtil(Context mContext, ImageView imageView) {
        String imageString = SharePreUtils.getString(mContext, Constant.IMAGE_TITLE, "");
        if (!imageString.equals("")) {
            byte[] byteArray = Base64.decode(imageString, Base64.DEFAULT);
            ByteArrayInputStream biStream = new ByteArrayInputStream(byteArray);
            Bitmap bitmap = BitmapFactory.decodeStream(biStream);
            imageView.setImageBitmap(bitmap);
        }
    }

}
